package cn.edu.hstc.wm.ui.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

import org.ksoap2.serialization.SoapObject;

import android.R.integer;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.SectionIndexer;
import android.widget.TextView;
import android.widget.Toast;
import cn.edu.hstc.wm.R;
import cn.edu.hstc.wm.adapter.StoreFragmentAdapter.ViewHolder;
import cn.edu.hstc.wm.bean.Category;
import cn.edu.hstc.wm.bean.Store;
import cn.edu.hstc.wm.service.StoreService;
import cn.edu.hstc.wm.ui.StoreItemActivity;
import cn.edu.hstc.wm.ui.base.BaseFragment;
import cn.edu.hstc.wm.utils.IntentUtil;
import cn.edu.hstc.wm.utils.LogUtil;
import cn.edu.hstc.wm.widget.CustomToast;
import cn.edu.hstc.wm.widget.PinnedSectionListView;
import cn.edu.hstc.wm.widget.PinnedSectionListView.PinnedSectionListAdapter;

/**
 * @ClassName: CategoryMode
 * @Description: 显示分类模式的Fragment
 * 
 * @ModificationHistory
 */
public class CategoryMode extends BaseFragment implements OnClickListener, OnItemClickListener {

	private static final String TAG = CategoryMode.class.getSimpleName();
	private static CategoryMode sFragment = null;

	private final int MSG_LOAD_FAILED = 0x00;
	private final int MSG_GET_CATEGORY = 0x01;
	private final int MSG_GET_STORES_OK = 0x02;
	private final int MSG_INIT_LISTVIEW = 0x03;

	/** 是否有头部和尾部 */
	private boolean hasHeaderAndFooter = false;
	/** 是否快速滚动 */
	private boolean isFastScroll = true;
	/** 是否添加padding */
	private boolean addPadding = false;
	/** 是否显示阴影 */
	private boolean isShadowVisible = true;

	/** 根视图 */
	private View mRootView;
	/** 正在加载界面 */
	private LoadingFragment mLoadingFragment;

	/** 具有固定分类的ListView */
	private PinnedSectionListView mListView;
	private CategoryAdapter mCategoryAdapter;

	/** 所有的店铺分类 */
	private List<Category> mCategories;

	/** 获取到的分类的所有店铺集合 ,用map来存放每个不同分类的Store集合 */
	private List<Map<String, List<Store>>> mStoresList;
	/** 每次不同分类的集合 */
	private List<Store> mItemStores;

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {

			// 加载失败
			case MSG_LOAD_FAILED:
				CustomToast.make(getActivity()).setText("GetCategoryTask  加载失败").show();
				break;

			// 加载店铺
			case MSG_GET_STORES_OK:
				if (mStoresList.size() > 0) {
					showLoadingView(false);
					initListView();
				} else {
					Toast.makeText(getActivity(), "load mStoresList failed ...", 1).show();
				}
				break;

			// 开始初始化ListView
			case MSG_INIT_LISTVIEW:
				initListView();
				break;

			default:
				break;
			}
		}
	};

	public static CategoryMode getInstance(Bundle bundle) {
		if (sFragment == null) {
			sFragment = new CategoryMode();
		}
		sFragment.setArguments(bundle);
		return sFragment;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		mRootView = inflater.inflate(R.layout.category_mode, null);

		// 正在加载...

		// 获取分类
		new GetCategoryTask().execute(0);

		return mRootView;
	}

	/**
	 * 设置是否显示正在加载界面
	 * 
	 * @param flag
	 *            true 显示正在加载 ;false 不显示正在加载
	 */
	private void showLoadingView(boolean flag) {
		if (flag) {
			// 正在加载页面显示
			mLoadingFragment = LoadingFragment.getInstance(getArguments());
			manageFragment(0x00, mLoadingFragment);
		} else {
			// 移除正在加载显示页面
			if (mLoadingFragment != null) {
				manageFragment(0x01, mLoadingFragment);
			}
		}
	}

	/*
	 * Fragment管理设置
	 * 
	 * @param type 动作类型: 0 -> remove ; 1 -> add ; 2 -> replace
	 * 
	 * @param fragment 需要管理的Fragment
	 */
	private void manageFragment(int type, Fragment fragment) {
		// 在Fragment中管理子Fragment是使用 getChildFragmentManager()
		FragmentTransaction transaction = getChildFragmentManager().beginTransaction();

		switch (type) {
		// remove
		case 0x01:
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
				// FIXME 错误
				// transaction.setCustomAnimations(R.animator.fragment_slide_left_enter,
				// R.animator.fragment_slide_left_exit);
			} else {
				transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
			}
			transaction.remove(fragment);
			// transaction.commit();
			break;

		// replace
		case 0x00:
			transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
			transaction.replace(R.id.fl_category_layout, fragment);
			// transaction.commit();
			break;
		default:
			break;
		}
		// 使用这个方法为了保证使用这个Fragment的Activity在保存状态后出现FC
		transaction.commitAllowingStateLoss();
	}

	private void initListView() {
		mListView = (PinnedSectionListView) mRootView.findViewById(android.R.id.list);

		initializeHeaderAndFooter();
		initializeAdapter();
		initializePadding();

		// 设置下拉滑动时的阴影效果
		mListView.setShadowVisible(isShadowVisible);
		mListView.setOnItemClickListener(this);
	}

	/** 初始化头部和尾部 */
	private void initializeHeaderAndFooter() {
		mListView.setAdapter(null);
		// 添加头部和尾部..
		if (hasHeaderAndFooter) {
			ListView list = mListView;
			LayoutInflater inflater = LayoutInflater.from(getActivity());
			TextView header1 = (TextView) inflater.inflate(android.R.layout.simple_list_item_1, list, false);
			header1.setText("First header");
			list.addHeaderView(header1);

			TextView header2 = (TextView) inflater.inflate(android.R.layout.simple_list_item_1, list, false);
			header2.setText("Second header");
			list.addHeaderView(header2);

			TextView footer = (TextView) inflater.inflate(android.R.layout.simple_list_item_1, list, false);
			footer.setText("Single footer");
			list.addFooterView(footer);
		}
	}

	/** 初始化Adapter */
	@SuppressLint("NewApi")
	private void initializeAdapter() {
		mListView.setFastScrollEnabled(isFastScroll);
		if (isFastScroll) {
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
				// mListView.setFastScrollAlwaysVisible(true);
			}

			mCategoryAdapter = new FastScrollAdapter(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1);
		} else {
			mCategoryAdapter = new CategoryAdapter(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1);
		}
		// 根据不同设置使用不同类型的适配器
		mListView.setAdapter(mCategoryAdapter);
	}

	/** 初始化ListView的内边距 */
	private void initializePadding() {
		float density = getResources().getDisplayMetrics().density;
		int padding = addPadding ? (int) (5 * density) : 0;
		mListView.setPadding(padding, padding, padding, padding);
	}

	@Override
	public void onClick(View v) {
		// TODO 不能直接使用position,
		// Toast.makeText(getActivity(),
		// mCategories.get(Integer.parseInt(v.getTag().toString())).getName(),
		// Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		Item item = (Item) parent.getItemAtPosition(position);
		if (item != null) {
			Toast.makeText(getActivity(), "欢迎进入" + item.mTitle, Toast.LENGTH_SHORT).show();
			LogUtil.d(TAG, "onItemClick position = " + position + "  id = " + id);
			// 点击中的item对应的store对象传递到另外一个Activity中
			Bundle bundle = new Bundle();
			bundle.putSerializable(StoreMode.INTENT_URL, (Store) ((Item) parent.getItemAtPosition(position)).mStore);
			IntentUtil.startActivity(getActivity(), StoreItemActivity.class, bundle);

		} else {
			// Toast.makeText(getActivity(), "Item " + position + " is null",
			// Toast.LENGTH_SHORT).show();
		}
	}

	private final class GetCategoryTask extends AsyncTask<Integer, Integer, List<Category>> {

		@Override
		protected List<Category> doInBackground(Integer... params) {
			try {
				return StoreService.getCategories();
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
		}

		@Override
		protected void onPreExecute() {
			showLoadingView(true);
		}

		@Override
		protected void onPostExecute(List<Category> result) {
			if (result != null) {
				for (int i = 0; i < result.size(); i++) {
					Log.d(TAG + " GetCategoryTask", result.get(i).toString());
				}
				// 初始化
				mCategories = result;
				mStoresList = new ArrayList<Map<String, List<Store>>>();
				new GetStoresTask().execute(0);

			} else {
				// 加载失败
				mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
			}
		}

	}

	private class GetStoresTask extends AsyncTask<Integer, Integer, List<Map<String, List<Store>>>> {

		@Override
		protected List<Map<String, List<Store>>> doInBackground(Integer... params) {

			try {
				return StoreService.getCategoryStores(mCategories);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(List<Map<String, List<Store>>> result) {
			if (result != null) {
				mStoresList = result;
				mHandler.sendEmptyMessage(MSG_GET_STORES_OK);
			} else {
				mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
			}

		}

	}

	/** 分类Item */
	private class Item {

		/** 是一个子项目Item的标记 */
		public static final int ITEM = 0;
		/** 是一个分类Item的标记 */
		public static final int SECTION = 1;

		public final int mType;
		public final String mTitle;
		public final Store mStore;

		public int sectionPosition;
		public int listPosition;

		public Item(int type, String text, Store store) {
			this.mType = type;
			this.mTitle = text;
			mStore = store;
		}

		@Override
		public String toString() {
			return mTitle;
		}

	}

	// test TODO 使用和Storemode 类似显示的子类部分内容适配器
	private class CateAdapter extends BaseAdapter implements PinnedSectionListAdapter {

		private Context mContext;

		private List<Map<Category, List<Store>>> mList;

		public CateAdapter(Context context, List<Map<Category, List<Store>>> list) {
			super();
			mContext = context;
			mList = list;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			return null;
		}

		protected void prepareSections(int sectionsNumber) {
		}

		protected void onSectionAdded(Item section, int sectionPosition) {
		}

		public int getViewTypeCount() {
			return 2;
		}

		@Override
		public int getItemViewType(int position) {
			return ((Item) getItem(position)).mType;
		}

		@Override
		public boolean isItemViewTypePinned(int viewType) {
			return viewType == Item.SECTION;
		}

	}

	/** 分类用的适配器 */
	private class CategoryAdapter extends ArrayAdapter<Item> implements PinnedSectionListAdapter {

		/** 分类颜色 */
		private final int[] COLORS = new int[] { R.color.category_1, R.color.category_2, R.color.category_3, R.color.category_4, R.color.category_5 };

		public CategoryAdapter(Context context, int resource, int textViewResourceId) {
			super(context, resource, textViewResourceId);

			// 分类数量
			int sectionsNumber = mStoresList.size();
			Log.d(TAG, "sectionsNumber = " + sectionsNumber);

			prepareSections(sectionsNumber);

			// 分类的位置,分类0,分类1,分类2...
			int sectionPosition = 0;
			// 在ListView中的位置
			int listPosition = 0;
			for (char i = 0; i < sectionsNumber; i++) {
				Item section = new Item(Item.SECTION, mCategories.get(i).getName(), null);
				section.sectionPosition = sectionPosition;
				section.listPosition = listPosition++;
				onSectionAdded(section, sectionPosition);
				add(section);

				// Log.d(TAG, "" + mStoresList.get(i).keySet().toString() +
				// "    " + mCategories.get(i).getId());
				mItemStores = mStoresList.get(i).get(mCategories.get(i).getId().toString());

				if (mItemStores == null) {
					continue;
				}
				// 子分类个数
				int itemsNumber = mItemStores.size();
				for (int j = 0; j < itemsNumber; j++) {
					Item item = new Item(Item.ITEM, mItemStores.get(j).getName(), mItemStores.get(j));
					item.sectionPosition = sectionPosition;
					item.listPosition = listPosition++;
					add(item);
				}

				sectionPosition++;
			}
		}

		protected void prepareSections(int sectionsNumber) {
		}

		protected void onSectionAdded(Item section, int sectionPosition) {
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			TextView view = (TextView) super.getView(position, convertView, parent);
			view.setTextColor(Color.DKGRAY);
			view.setTag("" + position);
			Item item = getItem(position);
			if (item.mType == Item.SECTION) {
				// 使用独立的监听器,避免分类和子类内容的错误,分类只是一个文字内容,而其子类包括了Store,需要分开处理点击事件
				view.setOnClickListener(CategoryMode.this);
				// 分类的颜色
				view.setBackgroundColor(parent.getResources().getColor(COLORS[item.sectionPosition % COLORS.length]));
			}
			return view;
		}

		@Override
		public int getViewTypeCount() {
			return 2;
		}

		@Override
		public int getItemViewType(int position) {
			return getItem(position).mType;
		}

		@Override
		public boolean isItemViewTypePinned(int viewType) {
			return viewType == Item.SECTION;
		}

	}

	/** 分类--快速滑动的适配器 */
	private class FastScrollAdapter extends CategoryAdapter implements SectionIndexer {

		private Item[] sections;

		public FastScrollAdapter(Context context, int resource, int textViewResourceId) {
			super(context, resource, textViewResourceId);
		}

		@Override
		protected void prepareSections(int sectionsNumber) {
			sections = new Item[sectionsNumber];
		}

		@Override
		protected void onSectionAdded(Item section, int sectionPosition) {
			sections[sectionPosition] = section;
		}

		@Override
		public Item[] getSections() {
			return sections;
		}

		@Override
		public int getPositionForSection(int section) {
			if (section >= sections.length) {
				section = sections.length - 1;
			}
			return sections[section].listPosition;
		}

		@Override
		public int getSectionForPosition(int position) {
			if (position >= getCount()) {
				position = getCount() - 1;
			}
			return getItem(position).sectionPosition;
		}

	}

}
